<?php
/**
 * Created by PhpStorm.
 * User: kaodou
 * Date: 2017/10/26
 * Time: 11:35
 */
namespace App\Api\Service\Category\Controllers;

use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\Category;
use App\Eloquent\Ygt\CategoryFields;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\DepartmentUser;
use App\Engine\Product as EngineProduct;
use App\Engine\Func;

class CategoryController extends Controller
{
    public $userId          = 25;
    /**
     * 获取下一级子分类
     */
    public function childList()
    {
        //获取用户id
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if(!$userId || !$userInfo )
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $companyId          = $userInfo->company_id;

        if($companyId == 2){
            //获取客户id
            $customerObj = \App\Eloquent\Ygt\Customer::where(['user_id'=>$userId])->first();
            if($customerObj){
                $companyId = $customerObj->company_id;
            }
        }

        $categoryId         = request('category_id',0);
        $where              = [
            'ygt_category.company_id'=>$companyId,
            'ygt_category.pid'=>$categoryId,
        ];
        $sonList            = Category::getJoinList($where)->toArray();
        $lists              = $sonIdArr = [];
        foreach($sonList as $key=>$val)
        {
            $temp           = $val;
            $imgPath        = Func::getImgUrlHttp($val['img_url']);
            $temp['image_path']         = $imgPath;
            $temp['img_path']           = $imgPath;
            $temp['cate_fields_arr']    = [];

            $lists[]        = $temp;
            $sonIdArr[]     = $val['id'];
        }
        //取分类自定义的属性
        $where              = ['category_id'=>['in',$sonIdArr]];
        $fieldsList         = CategoryFields::getList($where,'','','',['id','asc']);
        //给分类添加上其自定义的属性
        $lists              = Category::addCustomFieldsToList($lists,$fieldsList);
        return $lists;
    }

    public function getChildCategoryListWithProductList()
    {
        $category_id = request()->get('category_id', 0);

        //获取用户id
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId);
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //如果是客商，临时转换企业ID
        if($companyId == 2){
            //获取客户id
            $customerObj = \App\Eloquent\Ygt\Customer::where(['user_id'=>$userId])->first();
            if($customerObj){
                $companyId = $customerObj->company_id;
            }
        }


        $categoryModel = new Category();
        $CategoryList = $categoryModel->getChildrenList($category_id,true,$companyId);
        $productName = request('product_name');

        //是否隐藏添加按钮
        $isHideAddButton = 1;
//        if($userInfo['company_id'] == 2){
//            $isHideAddButton = 1;
//        }
        //只有下单人有创建材料权限
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $isHideAddButton = 0;
        }



        $CategoryList->transform(function ($item, $key) use ($category_id,$companyId,$productName,$isHideAddButton) {
            $categoryModel = new Category();
            $categoryArr = $categoryModel->getCategoryOption($item['id'],$companyId);
            $category = collect($categoryArr);

            $tempCategoryIds = $category->map(function ($c) {
                return $c['id'];
            })->toArray();

            

            $categoryIds = array_push($tempCategoryIds, $item['id']);
            if($category_id == $item['id']){
                $where['category_id'] = $category_id;
            }else{
                $where['category_id'] = ['in',$tempCategoryIds];
            }

            if ($productName) {
                $where['product_name'] = ['like', '%' . $productName . '%'];
            }

            $field = "ygt_product.id".
                ",ygt_product.product_name".
                ",ygt_product.product_no".
                ",ygt_product.barcode".
                ",ygt_product.number".
                ",ygt_product.warning_number".
                ",ygt_product.category_id".
                ",ygt_product.price".
                ",ygt_product.unit".
                ",ygt_product.created_at".
                ",ygt_img_upload.img_url";


            $productModel = new Product();
            $item['product_list'] = $productModel->getProList($where, $field,'','',['ygt_product.id','desc']);
            $item['product_list']->transform(function ($item, $key){
                $temp = $item->toArray();
                $item['image_path'] = Func::getImgUrlHttp($item['img_url']);
                $item['is_warning'] = $item['warning_number'] > $item['number'] ? 1 : 0;
                $item['is_new'] = (time() - $temp['created_at']) < 86400*7 ? 1 : 0;
                return $item;
            });
            $item['is_hide_add_button'] = $isHideAddButton;
            return $item;
        });
        return $CategoryList;
    }

    /**
     * 获取所有子分类树状
     */
    public function getTreeCategoryList()
    {
        $pid = request()->get('pid', 0);

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId);
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        if($companyId == 2){
            //获取客户id
            $customerObj = \App\Eloquent\Ygt\Customer::where(['user_id'=>$userId])->first();
            if($customerObj){
                $companyId = $customerObj->company_id;
            }
        }

        $categoryModel = new Category();
        $CategoryList = $categoryModel->getCategoryTree($pid,$companyId);
        return $CategoryList;
    }

    /**
     * 添加分类
     */
    public function addCategory(){
        $params = request()->only('pid','unit','display','cat_name');
        if($imgId = request('img_id',0)){
            $params['img_id'] = $imgId;
        }

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId);
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $params['company_id'] = $companyId;

        $params['pid'] = request('pid', 0);
        $rules = [
            'cat_name' => 'required',
            'pid' => 'required|integer',
            'display' => 'required|integer',
        ];
        $this->validateRequestParameters($params, $rules);

        $categoryModel = new Category();
        if($result = $categoryModel->addCategory($params)){
            return 'ok';
        }else{
            xThrow(ERR_CATEGORY_ADD_FAIL);
        }
    }

    public function editCategory(){
        $params = request()->only('pid','unit','display','cat_name','category_id');


        $params['pid'] = request('pid', 0);
        $rules = [
            'category_id' => 'required|integer',
            'cat_name' => 'required',
            'pid' => 'required|integer',
            'display' => 'required|integer',
        ];
        $this->validateRequestParameters($params, $rules);

        $where = ['id'=>$params['category_id']];
        $updateData = [
            'pid'=>$params['pid'],
            'cat_name'=>$params['cat_name'],
            'display'=>$params['display'],
            'unit'=>$params['unit'],
        ];

        if($imgId = request('img_id',0)){
            $updateData['img_id'] = $imgId;
        }

        $categoryModel = new Category();
        if($result = $categoryModel->updateCategory($updateData, $where)){
            return 'ok';
        }else{
            xThrow(ERR_CATEGORY_EDIT_FAIL);
        }
    }

    public function deleteCategory(){
        $params = request()->only('category_id');
        $rules = [
            'category_id' => 'required|integer',
        ];
        $this->validateRequestParameters($params, $rules);

        //先删除子分类的ID（暂时只支持2级分类）
        \App\Eloquent\Ygt\Category::where(['pid'=>$params['category_id']])->delete();

        $categoryModel = new Category();
        if($result = $categoryModel->delCategory($params['category_id'])){
            return 'ok';
        }else{
            xThrow(ERR_CATEGORY_DELETE_FAIL);
        }

    }


//    //停用20180530
//    public function getFieldsList(){
//        $params = request()->only('category_id');
//        $rules = [
//            'category_id' => 'required|integer',
//        ];
//        $this->validateRequestParameters($params, $rules);
//
////        $fieldsTypes = EngineProduct::fieldsType();
//
//        $CategoryFieldsModel = new CategoryFields();
//
//        $where = [
//            'category_id'=>$params['category_id']
//        ];
//        $fields = 'field_name,field_type,placeholder,is_must';
//        $list = $CategoryFieldsModel->getData($where,$fields,'','',['sort_id','asc']);
//        return $list;
//    }
    public function getFieldsList()
    {
        $params         = request()->only('category_id');
        $rules          = [
            'category_id' => 'required|integer',
        ];
        $this->validateRequestParameters($params, $rules);
        $result         = CategoryFields::getCustomFieldListByType($params['category_id']);
        return $result;
    }

}